<template>
  <div class="content">

    <div class="form">

      头像
      <div id='avatar-upload' style="display:inline-block">
        <el-upload action="#" :multiple='false' :auto-upload='false' list-type="picture-card" :limit='1' :file-list="avatarList"
          style="display: inline-block;" :class="{ hideUploadBtn: noneUploadBtn }" :on-change='avatarChange' :on-remove='avatarRemove'>
          <i slot="default" class="el-icon-plus"></i>
        </el-upload>
      </div>

      <el-form ref="formRef" :model="form" :rules="rules">
        <el-form-item label="用户名" prop="user_name">
          <el-input v-model="form.user_name"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="form.email"></el-input>
        </el-form-item>
        <el-form-item label="居住地" prop="address">
          <el-input v-model="form.address"></el-input>
        </el-form-item>
        <el-button type="primary" @click="submitForm()" style="background-color: #21bdd8; float:right">提交</el-button>
        <el-button @click="resetForm()" style="float:right; margin-right: 2%;">重置</el-button>
      </el-form>

    </div>
  </div>
</template>

<script>
import personalApi from "@/api/personal"
import loginApi from "@/api/login.js"

export default {
  data() {
    var validateName=(rule,value,callback) => {

      if(this.form.user_name!=this.user.user_name) {
        // 发请求，判断用户名是否存在
        loginApi.nameExist(this.form.user_name).then(res => {
          let sign=res.data.sign; // 返回false, 表示用户名已存在; 返回true, 表示用户名不存在
          if(sign) {
            callback();
          } else {
            callback(new Error("用户名已被注册"));
          }
        });
      }
      else callback();
    };
    return {
      avatarChanged: false,
      user: {},
      avatarList: [],
      noneUploadBtn: true,
      form: {
        user_name: '',
        phone: '',
        email: '',
        address: '',
      },
      rules: {
        user_name: [{ required: true,message: '用户名不能为空',trigger: 'blur' },{ min: 2,max: 10,message: '用户名长度需为2-10个字符',trigger: 'blur' },{ validator: validateName,trigger: 'blur' }],
        phone: [{ required: true,message: '手机号不能为空',trigger: 'blur' },{ min: 6,max: 20,message: '手机号长度需为6-20个字符',trigger: 'blur' }],
        email: [{ type: 'email',message: '邮箱格式不正确',trigger: 'blur' }],
      }
    }
  },
  methods: {
    //加载用户信息
    load_userInfo() {
      personalApi.getInfo().then(res => {
        this.user=res.data;
        setTimeout(() => {
          this.setFileList()
          this.form.user_name=this.user.user_name
          this.form.phone=this.user.phone
          this.form.email=this.user.email
          this.form.address=this.user.address
        },0)
      });
    },

    //文件列表移除文件时的钩子, 添加文件时会被调用
    avatarChange(file,fileList) {
      this.avatarChanged=true,
        this.noneUploadBtn=fileList.length==1
      this.avatarList=fileList
    },

    //文件列表移除文件时的钩子
    avatarRemove(file,fileList) {
      this.noneUploadBtn=fileList.length==1
      this.avatarList=fileList
    },

    setFileList() {
      if(this.avatarList=='') {
        var avatar={
          name: 'avatar',
          url: this.user.avatar
        }
        this.avatarList.push(avatar)
      }
    },

    submitForm() {
      this.$refs.formRef.validate(
        async (valid) => {
          if(valid) {
            //提交用户信息
            personalApi.updateUser(this.form.user_name,this.form.phone,this.form.email,this.form.address)
              .then(async res => {
                if(res.data.msg===1) {
                  //提交用户头像
                  let data={}
                  if(this.avatarChanged) {
                    data.avatar=this.avatarList[0].raw;
                    const avatar=await personalApi.updateAvatar(data)
                  }
                  this.$message.success('用户信息修改成功');
                  this.load_userInfo();
                  location.reload()

                } else {
                  this.$message.error('用户信息修改失败');
                }
              })
          }
        }
      )


    },

    async resetForm() {
      await this.load_userInfo()
      this.$refs.formRef.resetFields();
    }
  },
  mounted() {
    this.load_userInfo()
  }
}

</script>

<style lang=scss scoped>
.content {
  height: 728px;
  background-color: rgba(34, 52, 87, 0.6);
}

#avatar-upload {
  /* 回显图片 */
  ::v-deep .el-upload-list--picture-card {
    margin-left: 14px;
  }

  /* 上传按钮 */
  ::v-deep .el-upload--picture-card {
    background-color: rgba(30, 117, 164, 0.5);
    border: 1px dashed #1e75a4;
  }

  ::v-deep .hideUploadBtn .el-upload--picture-card {
    display: none;
  }
}

.form {
  padding-top: 4%;
  width: 50%;
  margin: auto;
}
</style>